const Koa = require('koa')

// 注意require('koa-router')返回的是函数:
const router = require('koa-router')()
const app = new Koa()

// 全局处理所有中间件错误
app.use(async (ctx, next) => {
  try {
    console.log(`Process ${ctx.request.method} ${ctx.request.url}...`)
    await next()
  } catch (error) {
    ctx.status = 500
    ctx.body = error.message
  }
})

const index = require('./index')
const video = require('./video')
const tag = require('./tag')
const space = require('./space')
const search = require('./search')
const rank = require('./rank')
const article = require('./article')
const comment = require('./comment')
const vote = require('./vote')
const topic = require('./topic')
const bangumi = require('./bangumi')
const channel = require('./channel')
const lottery = require('./lottery')
router.use('/api/index', index.routes())
router.use('/api/video', video.routes())
router.use('/api/tag', tag.routes())
router.use('/api/space', space.routes())
router.use('/api/search', search.routes())
router.use('/api/rank', rank.routes())
router.use('/api/article', article.routes())
router.use('/api/comment', comment.routes())
router.use('/api/vote', vote.routes())
router.use('/api/topic', topic.routes())
router.use('/api/bangumi', bangumi.routes())
router.use('/api/channel', channel.routes())
router.use('/api/lottery', lottery.routes())
router.get('/', async (ctx, next) => {
  ctx.response.body = '<h1>Index</h1>'
})
// add router middleware:
app.use(router.routes()).use(router.allowedMethods())
app.listen(3000)
console.log('server started at port 3000...')
